<template>
  <view class="weather">
    <!-- 顶部地址信息等菜单栏 -->
    <view class="top">
      <view class="citylist d-flex ai-center text-center">
        <view class="address text-center m0a" @click="refreshNow">{{city.adm2}}市{{city.name}}区</view>
        <i class="iconfont icon-iconfontarrows" @click="select"></i>
      </view>
      <!-- 城市列表 -->
      <view class="list card m0a" v-if="selected == true">
        <view class="wrap d-flex jc-between ai-center">
          <view class="title">我关注的城市</view>
          <view class="close" @click="close">×</view>
        </view>
        <view
          class="mylist text-center"
          v-for="(item,index) in citylist"
          :key="index"
          @click="changeCity(item)"
        >{{item.adm2}}{{item.name}}</view>
        <view class="hotcity">热门城市</view>
        <view
          class="mylist text-center"
          v-for="(item,index) in hotcity"
          :key="index"
          @click="changeCity(item)"
        >{{`${item.adm1}${item.name}`}}</view>
      </view>
      <view class="morecity iconfont icon-jia" @click="choseOthercity"></view>
    </view>
    <!-- 实况天气 -->
    <view class="card now m0a d-flex ai-center">
      <view class="title">实况天气</view>
      <image class="refresh" @click="refresh" src="../../../static/refresh.png" />
      <image
        :src="`	https://pics-1257236742.cos.ap-nanjing.myqcloud.com/%E5%B0%8F%E7%A8%8B%E5%BA%8F%E5%9B%BE%E5%BA%8A/${now.icon}.png`"
      />
      <!-- 温度 -->
      <view class>
        <view class="det d-flex ai-center">
          <view class="temp">{{now.temp}}</view>
          <view class="other">
            <!-- 天气状况文字描述 -->
            <view class="text">{{now.text}}</view>
            <!-- 风 -->
            <view class="wind">{{now.windDir}}{{now.windScale}}级</view>
          </view>
        </view>
        <!-- 更新时间 -->
        <view class="feeltemp">体感温度：{{now.feelsLike}}</view>
        <view class="time">更新时间：{{now.obsTime | moment('MM-DD h:mm')}}</view>
      </view>
    </view>

    <!-- 未来24小时 -->
    <view class="24hour card m0a d-flex">
      <view class="title">未来24小时预报</view>
      <view class="hours">
        <view class="h_item d-flex ai-center" v-for="(item,index) in hours" :key="index">
          <view class="time">{{item.fxTime | moment('MM-DD hh:mm a')}}</view>
          <view class="temprature">{{item.temp}}℃</view>
          <image
            class="sm_icon"
            :src="`https://pics-1257236742.cos.ap-nanjing.myqcloud.com/%E5%B0%8F%E7%A8%8B%E5%BA%8F%E5%9B%BE%E5%BA%8A/${item.icon}.png`"
          />
          <view class="text">{{item.text}}</view>
        </view>
      </view>
    </view>

    <!-- 未来三天预报 -->
    <view class="3days card m0a d-flex">
      <view class="title">未来三天预报</view>
      <view class="daily_item" v-for="(item,index) in daily" :key="index">
        <image
          class="icon"
          :src="`	https://pics-1257236742.cos.ap-nanjing.myqcloud.com/%E5%B0%8F%E7%A8%8B%E5%BA%8F%E5%9B%BE%E5%BA%8A/${item.iconDay}.png`"
        />
        <!-- 天气文字描述 -->
        <view class="text text-center">{{item.textDay}}</view>
        <!-- 温度区间 -->
        <view class="temprange text-center">{{item.tempMax}}℃ ~ {{item.tempMin}}℃</view>
        <view class="date text-center">{{item.fxDate}}</view>
      </view>
    </view>

    <!-- 生活指数 -->
    <view class="indica card m0a">
      <view class="title">生活指数参考</view>
      <view class="indica_item" v-for="(item,index) in indice" :key="index">
        <view class="item_name">{{item.name}}:</view>
        <view class="item_det">
          <view class="category">等级：{{item.category}}</view>
          <view class="text">详细描述：</view>
          <view class="text">{{item.text}}</view>
        </view>
      </view>
    </view>
    <!-- 数据来源 -->
    <view class="from card m0a">
      <view class="info">注：天气数据来源：和风天气开发版api，不用于商业用途</view>
    </view>
  </view>
</template>

<script>
// 引入和风天气的api
import hefeng from "../../../api/weather/hefeng";
import moment from "moment";
// 下拉菜单
export default {
  data() {
    return {
      // 当前城市的经纬度
      latitude: "",
      longtitude: "",
      // 当前城市信息
      city: {},
      // 当前城市的locationId
      locationId: "",
      // 实况天气信息
      now: {},
      // 未来3天
      daily: [],
      // 当天生活指数
      indice: [],
      // 24小时
      hours: [],
      // 添加过的城市列表
      citylist: [],
      defaultIndex: [0, 0],
      // 是否展示下拉城市列表选择菜单
      selected: false,
      // 热门城市
      hotcity: [],
    };
  },
  async mounted() {
    // 检测定位权限，获取定位
    this.makeSureAdd();
    // 更新一下热门城市
    const res = await hefeng.hotCitylist();
    this.hotcity = res.topCityList;
  },
  methods: {
    // 检测是否已经授权获取当前定位
    makeSureAdd() {
      let that = this;
      wx.getSetting({
        success(res) {
          // 如果已授权，直接获取位置信息
          if (res.authSetting["scope.userLocation"]) {
            that.getLocation();
          } else {
            // 申请授权并获取
            wx.authorize({
              scope: "scope.userLocation",
              success() {
                that.getLocation();
              },
              fail() {
                console.log("用户取消了授权");
                // 给一个重新授权的机会
              },
            });
          }
        },
      });
    },
    // 获取定位信息 以及城市信息
    getLocation() {
      let that = this;
      wx.getLocation({
        type: "wgs84",
        async success(res) {
          that.latitude = res.latitude;
          that.longitude = res.longitude;
          const res1 = await hefeng.cityInfo(
            `${that.longitude},${that.latitude}`
          );
          that.city = res1.location[0];
          that.locationId = res1.location[0].id;
          that.citylist.push(res1.location[0]);
          uni.setStorageSync("citylist", that.citylist);
          that.getNowweather(that.locationId);
          that.initDate();
        },
      });
    },
    // 获取实况天气
    async getNowweather(id) {
      const res = await hefeng.getNowWeather(id);
      console.log(res);
      this.now = res.now;
    },
    // 更新天气
    async refresh() {
      uni.showToast({
        title: "实况天气更新中",
        icon: "loading",
        duration: 1500,
      });
      this.getNowweather(this.locationId);
    },
    // 各种数据的初始化
    async initDate() {
      const res2 = await hefeng.get3dayWeather(this.locationId);
      this.daily = res2.daily;
      const res3 = await hefeng.indiceToday(this.locationId);
      this.indice = res3.daily;
      const res4 = await hefeng.get24HWeather(this.locationId);
      this.hours = res4.hourly;
    },
    // 刷新当前城市的数据
    async refreshNow() {
      uni.showToast({
        title: "数据更新中",
        icon: "loading",
        duration: 1500,
      });
      this.initDate();
    },
    // 选择其他城市
    choseOthercity() {
      let that = this;
      uni.chooseLocation({
        success: async function (res) {
          // 获取城市信息 使用和风天气api
          const res1 = await hefeng.cityInfo(
            `${res.longitude},${res.latitude}`
          );
          that.city = res1.location[0];
          that.locationId = res1.location[0].id;
          that.citylist.push(res1.location[0]);
          uni.setStorageSync("citylist", that.citylist);
          that.getNowweather(that.locationId);
          that.initDate();
        },
      });
    },
    // 选择城市列表的显示
    select() {
      this.selected = true;
    },
    // 切换城市
    changeCity(city) {
      // 点击完关闭筛选框
      this.selected = false;
      uni.showToast({
        title: "信息查询中",
        icon: "loading",
        duration: 500,
      });
      // 传入的city为经过和风api查询出来的城市信息
      this.locationId = city.id;
      this.city = city;
      // 查询各种数据重新
      this.initDate();
    },
    // 关闭筛选框
    close() {
      this.selected = false;
    },
  },
};
</script>

<style lang='scss'>
@import "./index";
.top {
  .list {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    top: 0em;
    z-index: 10;
    padding-top: 1em;
    background-color: rgba(8, 8, 8, 0.9);
    margin-bottom: 2em;
    .mylist {
      margin-bottom: 1em;
    }
    .wrap {
      .title {
        position: static;
      }
      .close {
        font-size: 60rpx;
        font-weight: bolder;
      }
    }
  }
}
</style>